package study.kit.el.zh.table;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.NumberUtil;
import lombok.extern.slf4j.Slf4j;
import study.kit.el.zh.parse.RangeVO;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class AlignUtil {

    public static List<AlignVO> getAlignLt(List<RangeVO> rangeVOLt) {
        return rangeVOLt.stream()
                .map(e -> AlignVO.builder()
                        .colNum(e.getColNum())
                        .rowStart(e.getRowNum())
                        .rowEnd(e.getRowNum() + e.getRowCnt() - 1)
                        .size(e.getRowCnt())
                        .build())
                .collect(Collectors.toList());
    }

    /**
     * 如: 1 2 3 4 5
     * 外遍历: 1 2 3 4
     * 内遍历: 2 3 4 5
     */
    public static void check(List<AlignVO> alignVOLt) {
        // 排序
        CollectionUtil.sortByProperty(alignVOLt, "colNum");
        //
        int size = CollectionUtil.size(alignVOLt);
        List<AlignVO> memoLt = ListUtil.toList(); // 备忘
        for (int i = 0; i < size - 1; i++) {
            AlignVO VO1 = alignVOLt.get(i);
            // 区间
            Integer rowStart = VO1.getRowStart();
            Integer rowEnd = VO1.getRowEnd();
            //
            for (int j = 1; j < size; j++) {
                AlignVO VO2 = alignVOLt.get(j);
                //
                if (NumberUtil.equals(VO1.getColNum(), VO2.getColNum()) || memoLt.contains(VO1) || memoLt.contains(VO2)) {
                    //log.info("fffffffff");
                    continue;
                }
                // 区间
                Integer curRowStart = VO2.getRowStart();
                Integer curRowEnd = VO2.getRowEnd();
                //
                boolean isCross = (curRowStart >= rowStart && curRowStart <= rowEnd) ||
                        (curRowEnd >= rowStart && curRowEnd <= rowEnd);
                if (isCross && !NumberUtil.equals(VO1.getSize(), VO2.getSize())) {
                    memoLt.add(VO1);
                    memoLt.add(VO2);
                    log.info("第 {} 列行({}, {}) 和 第 {} 列行({}, {}) 未对齐",
                            VO1.getColNum(), rowStart, rowEnd, VO2.getColNum(), curRowStart, curRowEnd);
                }
            }
        }
    }
}
